package com.yuzhyn.hiops.app.manager;

import com.yuzhyn.azylee.core.datas.strings.StringTool;
import com.yuzhyn.azylee.websdk.args.WebSdk;
import com.yuzhyn.azylee.websdk.args.WebSdkStarter;
import com.yuzhyn.hiops.app.aarg.R;
import com.yuzhyn.hiops.common.entity.SysMachine;
import com.yuzhyn.hiops.common.mapper.SysMachineMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

@Slf4j
@Component
public class AppLiveManager {

    @Autowired
    private SysMachineMapper sysMachineMapper;

//    @Autowired
//    private DbUpdateTool dbUpdateTool;

    @PostConstruct
    public void init() throws Exception {
        log.info("********** 系统启动中 **********");

        // sqlite数据库升级
//        dbUpdateTool.update();


        // 程序机器id初始化
        if (StringTool.ok(WebSdk.MachineId())) {
            SysMachine sysMachine = sysMachineMapper.selectById(WebSdk.MachineId());
            if (sysMachine == null) {
                sysMachine = new SysMachine();
                sysMachine.setMachineId(WebSdk.MachineId());
                sysMachine.setIp("127.0.0.1");
                sysMachine.setMac("00:00:00:00:00:00");
                sysMachine.setDataCenterId(-1);
                sysMachine.setWorkerId(-1);
                sysMachineMapper.insert(sysMachine);
            }
            WebSdkStarter.run(sysMachine.getDataCenterId(), sysMachine.getWorkerId());
        }


    }

    /**
     * 系统优雅关闭，统一触发
     */
    @PreDestroy
    public void destroy() {
        log.info("********** 系统退出 **********");
        long now = System.currentTimeMillis();
        log.info("==============================================");
        log.info("======== AppLiveManager 正在关闭..... ========");
        log.info("==============================================");

        // 此处做可执行的善后处理
        R.Cache.CacheManager.close();

        log.info("==============================================");
        log.info("======== AppLiveManager 已经关闭 =============");
        log.info("==============================================");
        log.info("Time spent: " + (System.currentTimeMillis() - now));
    }

}
